<template>
  <div class="app-container">
    <div style="font-size: 25px;">添加销售订单</div>
    <el-divider></el-divider>
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="销售单号" style="width: 400px" prop="saleNumber"
                        :rules="[{ required: true ,message: '请输入销售单号'}]">
            <el-input v-model="saleOrderNum" placeholder="请输入销售单号" maxlength="15" required="required"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户" style="width: 400px" prop="customerId"
                        :rules="[{ required: true ,message: '请选择客户'}]">
            <el-select
              v-model="form.customerId"
              placeholder="请选择客户"
              clearable
              size="small"
              style="width: 100%"
              @change="getInfo(form.customerId)"
            >
              <el-option
                v-for="dict in customerList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="客户手机" style="width: 400px" prop="customerPhone">
            <el-input v-model="customerTelephone" placeholder="请输入客户手机" @input="v => customerTelephone = v.replace(/[^\d]/g,'')"
                      maxlength="11"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="收获地址" style="width: 400px" prop="customerAddress">
            <el-cascader
              style="width: 100%"
              expand-trigger="hover"
              ref="cascaderAddr"
              size="small"
              :options="options"
              v-model="selectedOptions"
              @change="handleChange">
              <template slot-scope="{ node, data }">
                <span>{{ data.label }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="详细地址" style="width: 400px" prop="detailedAddress">
            <el-input v-model="detailedAdd" placeholder="请输入详细地址" maxlength="30"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="固定电话" style="width: 400px" prop="fixedTelephone">
            <el-input v-model="form.fixedTelephone" placeholder="请输入固定电话"  @input="v => form.fixedTelephone = v.replace(/[^\d]/g,'')"
                      maxlength="11"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>

        <el-col :span="8">
          <el-form-item label="收款方式" style="width: 400px" prop="paymentMethod">
            <el-select v-model="form.paymentMethod" placeholder="请选择收款方式" style="width: 100%" clearable>
              <el-option
                v-for="dict in dict.type.erp_payment_type"
                :key="dict.value"
                :label="dict.label"
                :value="parseInt(dict.value)"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" style="width: 400px" prop="customerContact">
            <el-input v-model="form.customerContact" placeholder="请输入简要备注" maxlength="200"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-divider></el-divider>
      <el-row style="margin-bottom: 20px;">
        <el-col :span="1.5">
          <div style="font-size: 20px; margin-top: 5px">销售商品</div>
        </el-col>
        <el-col :span="5">
          <el-button type="primary" @click="handleAdd" style="margin-left: 20px;">点击添加商品</el-button>
        </el-col>
      </el-row>

      <div style="margin-top:10px;">
        <el-table :data="addGoodsList" show-summary :summary-method="getSummaries">
          <el-table-column label="商品ID" align="center" prop="id"/>
          <el-table-column label="商品名称" align="center" prop="name"/>
          <el-table-column label="分类" align="center" prop="categoryName"/>
          <el-table-column label="品牌" align="center" prop="brandName"/>
          <el-table-column label="单位" align="center" prop="companyName"/>
          <el-table-column label="库存" align="center" prop="inventory"/>
          <el-table-column label="成本单价" align="center" prop="cost"/>
          <el-table-column label="销售单价" align="center" prop="price">
            <div class="item" slot-scope="scope">
              <el-input class="item__input" v-model="scope.row.price" placeholder="请输入价格" size="mini"
                        style="width:100px" @input="handleEdit(scope.$index, scope.row)"
                        @keyup.native="scope.row.price = scope.row.price = scope.row.price.replace(/[^\d.]/g,'');
                                   scope.row.price = scope.row.price.replace(/\.{2,}/g,'.');
                                   scope.row.price = scope.row.price.replace(/^\./g,'');
                                   scope.row.price = scope.row.price.replace('.','$#$').replace(/\./g,'').replace('$#$','.');
                                   scope.row.price = scope.row.price.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');"
                        maxlength="15"></el-input>
            </div>
          </el-table-column>
          <el-table-column label="销售数量" align="center" prop="quantity">
            <div class="item" slot-scope="scope">
              <el-input-number v-model="scope.row.quantity" controls-position="right"
                               oninput="value=value.replace(/[^0-9.]/g,'')" :min="1" :max="scope.row.inventory" size="mini" style="width:100px"
                               @input="handleEdit(scope.$index, scope.row)"/>
            </div>
          </el-table-column>
          <el-table-column label="销售总价" align="center" prop="oneGoodPrice">
            <div class="item" slot-scope="scope">
              <el-input class="item__input" v-model="scope.row.oneGoodPrice" placeholder="销售总价" size="mini"
                        style="width:100px" readonly="readonly"></el-input>
            </div>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="text"
                icon="el-icon-error"
                @click="deleteGoodsList(scope.row)"
              >删除商品
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-form>

    <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
      <el-button type="primary" @click="submitForm">保存销售订单</el-button>
    </div>
    <!-- 添加或修改销售商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" :close-on-click-modal = "false" width="1500px" append-to-body>
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="商品名称" prop="name">
          <el-input
            v-model="queryParams.name"
            placeholder="请输入商品名称"
            clearable
            maxlength="35"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="品牌" prop="brandId">
          <el-select
            v-model="queryParams.brandId"
            placeholder="请选择品牌"
            clearable
            size="small"
            style="width: 240px"
            @keyup.enter.native="handleQuery"
          >
            <el-option
              v-for="dict in brandList"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="上下架" prop="shelves">
          <el-select
            v-model="queryParams.shelves"
            placeholder="请输入上下架"
            clearable
            @keyup.enter.native="handleQuery"
          >
            <el-option label="上架" value=1 />
            <el-option label="下架" value=0 />
          </el-select>
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <treeselect v-model="queryParams.categoryId" :options="categoryOptions" :normalizer="normalizer"
                      placeholder="选择分类"
                      style="width: 230px;"/>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="loading" :data="goodsList">
        <el-table-column label="商品ID" align="center" prop="id"/>
        <el-table-column label="商品名称" align="center" prop="name"/>
        <el-table-column label="分类" align="center" prop="categoryName"/>
        <el-table-column label="品牌" align="center" prop="brandName"/>
        <el-table-column label="单位" align="center" prop="companyName"/>
        <el-table-column label="库存" align="center" prop="inventory"/>
        <el-table-column label="成本单价" align="center" prop="cost"/>
        <el-table-column label="商品价格" align="center" prop="price"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-circle-plus-outline"
              @click="addGood(scope.row)"
            >添加商品
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getGoodList"
      />
      <div slot="footer" class="dialog-footer" style="text-align:center;margin-top: 20px;">
        <!--        <el-button type="primary" @click="addGoodList">选择商品添加</el-button>-->
        <el-button @click="cancelGoods">关闭页面</el-button>
      </div>
    </el-dialog>

  </div>

</template>

<script>

import {getCustomer, listCustomer} from "@/api/erp/customer";
import {CodeToText, regionData} from "element-china-area-data";
import {addGoods, listGoods} from "@/api/erp/goods";
import {listCategory} from "@/api/erp/category";
import {listBrand} from "@/api/erp/brand";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {addSale} from "@/api/erp/sale";

let stream = require('stream')

export default {
  name: "sale",
  components: {Treeselect},
  dicts: ['erp_payment_type'],
  data() {
    return {
      //销售单号
      saleOrderNum:null,
      //品牌列表
      brandList: [],
      //elementUi地区数据
      options: regionData,
      //分类列表
      categoryOptions: [],
      //客户列表
      customerList: [],
      //客户电话
      customerTelephone: null,
      //客户地址
      detailedAdd: null,
      // 商品信息表格数据
      goodsList: [],
      // 添加的商品信息表格数据
      addGoodsList: [],
      //客户省市区
      selectedOptions: [],
      // 总条数
      total: 0,
      //表单参数
      form: {},
      //商品表单参数
      goodsForm: {},
      // 显示搜索条件
      showSearch: true,
      // 遮罩层
      loading: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      //表单校验
      rules: {},
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        brandId: null,
        categoryId: null,
        type: null,
        labels: null,
        barCode: null,
        shelves:null,
      },
    };
  },
  created() {
    //查询客户列表
    this.selectCustomer();
    //获取随机销售单号
    this.getCurrentTime();
  },

  methods: {
    //保存销售订单提交按钮
    submitForm() {
      if (this.saleOrderNum == undefined) {
        this.$modal.msgError("请填写销售单号");
        return;
      }
      if (this.form.customerId == undefined) {
        this.$modal.msgError("请选择客户");
        return;
      }
      if (this.customerTelephone.length == 0) {
        this.$modal.msgError("请填写客户手机号");
        return;
      }
      if (this.selectedOptions == undefined) {
        this.$modal.msgError("请填写收货地址");
        return;
      }
      if (this.detailedAdd.length == 0) {
        this.$modal.msgError("请填写详细地址");
        return;
      }
      if (this.addGoodsList.length === 0) {
        this.$modal.msgError("请添加商品");
        return;
      }
      this.form.customerPhone = this.customerTelephone;
      this.form.goodsList = this.addGoodsList;
      this.form.saleNumber = this.saleOrderNum;
      addSale(this.form).then(response => {
        if (response.code === 200) {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.close();
        }
      });
    },
    //新增商品按钮操作
    handleAdd() {
      this.getBrandList();
      this.getCategoryList();
      this.getGoodList();
      this.open = true;
      this.title = "添加商品";
    },
    //添加商品方法
    addGood(row) {
      for (var i = 0; i < this.addGoodsList.length; i++) {
        let newVar = this.addGoodsList[i];
        if (row.id === newVar.id) {
          this.$modal.msgError("以添加过此商品!");
          return;
        }
      }
      console.log(row.inventory+"-------")
      if (row.inventory <= 0){
        this.$modal.msgError("库存不足!");
        return;
      }
      this.goodPrice = row.price;
      this.addGoodsList.push(row);
    },
    //删除添加的商品方法
    deleteGoodsList(row) {
      this.addGoodsList.splice(this.addGoodsList.indexOf(row), 1);
    },
    //查看商品详情按钮操作
    handleInfo(row) {
      this.$router.push({path: '/infoGoods', query: {id: row.id}});
    },
    //查询商品列表
    getGoodList() {
      this.loading = true;
      listGoods(this.queryParams).then(response => {
        this.goodsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //商品总价计算
    handleEdit(index, row) {
      if (row.quantity && row.price) {
        row.oneGoodPrice = Number(row.quantity) * Number(row.price)
      }
    },
    //查询客户列表
    selectCustomer() {
      listCustomer(this.queryParams).then(response => {
        this.customerList = response.rows;
      });
    },
    //获取客户信息
    getInfo(row) {
      const id = row
      getCustomer(id).then(response => {
        this.customerTelephone = response.data.phone
        this.detailedAdd = response.data.detailedAddress
        this.form.province = response.data.province
        this.form.city = response.data.city
        this.form.area = response.data.area
        this.form.detailedAddress = response.data.detailedAddress
        this.form.customerAddress = response.data.customerAddress
        this.selectedOptions = [response.data.province.toString(), response.data.city.toString(), response.data.area.toString()]
      });
    },
    //获取分类列表
    getCategoryList() {
      let params = {};
      listCategory(params).then(response => {
        this.categoryOptions = this.handleTree(response.data, "id", "parentId");
      });
    },
    //获取随机订单编号
    getCurrentTime() {
      //获取当前时间并打印
      var _this = this;
      let yy = new Date().getFullYear().toString();
      let mm = (new Date().getMonth()+1).toString();
      let dd = new Date().getDate().toString();
      let hh = new Date().getHours().toString();
      let mf = (new Date().getMinutes()<10 ? '0'+new Date().getMinutes() : new Date().getMinutes()).toString();
      let ss = (new Date().getSeconds()<10 ? '0'+new Date().getSeconds() : new Date().getSeconds()).toString();
      _this.saleOrderNum = "Son"+yy+mm+dd+hh+mf+ss+ Math.floor(Math.random() * 10000)
    },
    //node分类节点
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    //查询品牌列表
    getBrandList() {
      let params = {};
      listBrand(params).then(response => {
        this.brandList = response.rows;
      });
    },
    //elementUi选择地址
    handleChange(value) {
      this.selectedOptions = value
      var name = ''
      this.selectedOptions.map(item =>
        name += CodeToText[item] + '') //将省市区三个拼接一起
      this.form.province = value[0];
      this.form.city = value[1];
      this.form.area = value[2];
      this.form.customerAddress = name;
    },
    //搜索按钮操作
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getGoodList();
    },
    // 重置按钮操作
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    //返回上一页商品列表页
    close() {
      this.$router.push({path: '/saleList'});
    },
    //商品小计
    getSummaries(param) {
      const {columns, data} = param;
      const sums = []; //声明变量
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = "小计";
          return;
        }
        const values = data.map((item) => Number(item[column.property]));
        if (
          column.property === "oneGoodPrice"
        ) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);
        } else {
          sums[index] = '';
        }
      });
      return sums;
    },
    //关闭弹出框
    cancelGoods(){
      this.open = false;
    }

  }
}

</script>

